package C049;

/**
 * ClassName: C04
 * Package: C049
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/17 10:54
 * @Version 1.0
 * @Since 1.0
 */
public class C04 {
    public static void main(String[] args) {
        int[] arr = {5,1,2,3,4};
        int[] arr2 = {4,4,1,5,1};
        System.out.println(canCompleteCircuit(arr, arr2));
    }


    public static int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0, len = 0;
        for (int l = 0, r = 0; l < gas.length; l++) {
            while (sum >= 0) {
                if(len == gas.length) {
                    return l;
                }
                r %= gas.length;
                sum += (gas[r] - cost[r]);
                r++;
                len ++;
            }
            sum -= (gas[l] - cost[l]);
            len--;
        }

        return -1;
    }

//    public static int canCompleteCircuit(int[] gas, int[] cost) {
//        int[] mod = new int[gas.length];
//        for (int i = 0; i < gas.length; i++) {
//            mod[i] = gas[i] - cost[i];
//        }
//        int sum = 0;
//        int maxIndex = 0;
//        for (int i = 0; i < mod.length; i++) {
//            sum += mod[i];
//            if(mod[i] > mod[maxIndex]) {
//                maxIndex = i;
//            }
//        }
//
//        return sum >= 0 ? maxIndex : -1;
//    }

}
